package com.ipay.wechat.factory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ipay.redis.JedisExecutor;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.dao.MessagePushDao;
import com.ipay.wechat.pojo.MessagePush;
import com.ipay.wechat.service.MerchantInfoService;
import com.ipay.wechat.service.TradeRecordService;
import com.ipay.wechat.util.HttpUtils;
import com.ipay.wechat.util.PushMessage;

@Service("messageTask")
public class MessageTask {
	
	@Autowired
	private MessagePushDao messagePushDao;
	
	@Autowired
	private Wechat wechat;
	
	@Autowired
	private JedisExecutor jedies;
	@Autowired
	private TradeRecordService tradeRecordService;
	@Autowired
	private MerchantInfoService merchantInfoService;
	
	/*private ApplicationContext context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");*/
	
	public void initConsumer(){
		merchantInfoService.kafkaConsumer();
	}
	
	public void sendMessage() {
		String access_token = tradeRecordService.getAccessToken();

		int status = 0;
		List<MessagePush> list = messagePushDao.findListByStatus(status);
		if(list.size()>0){
			for(MessagePush msg : list){
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("index", "1");
				map.put("openid", msg.getOpenid());
				
				SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日 "); 
				String nowDate = format1.format(new Date());
				
				map.put("tempCode", wechat.getTEMPLATE1());
				map.put("first", msg.getTitle());
				map.put("keyword1", nowDate);
				map.put("keyword2", msg.getContent());
				map.put("remark", "");
				map.put("sendType", "0");
				
				String message = PushMessage.createMsgJson(map);
				String result = HttpUtils.requestHttp("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token, "post", message);
				JSONObject jsonObj = new JSONObject(result);
				int errCode = (int) jsonObj.get("errcode");
				if(errCode == 0){
					msg.setStatus(1);
					messagePushDao.update(msg);
				}
			}
		}
	}
}
